package bim.web.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import keter.domain.Account;
import keter.domain.validation.BeanValidators;
import keter.service.AccountService;
import keter.service.RoleService;
import keter.service.UnitService;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import bim.domain.User;
import bim.service.UserService;

@Controller
@RequestMapping("/regist")
public class RegistController extends BaseController {
        
    @Autowired
    AccountService as;
    
    @Autowired
    UserService us;
    
    @Autowired
	UnitService uns;
    
    @Autowired
    RoleService rService;

    private static final Logger logger = LoggerFactory.getLogger(RegistController.class);

    public RegistController() {
    }
    
    public static class Views {
        private static final String Prefix = "regist";
        static final String Index = to_(Prefix) + "index";
        static final String Add = to_(Prefix) + "add";
    }

    /**
     * <p>Method ：add
     * <p>Description : 进入注册页面
     *
     * @param model
     * @return 
     * @author  顾力行-gulixing@msn.com
     */
    @RequestMapping(value = Routes.Index, method = RequestMethod.GET)
    public String index() {
//        logger.info("info");
//        logger.error("error");
        return Views.Index;
    }
    
    
    /**
     * <p>Method ：add
     * <p>Description : 
     *
     * @param model
     * @return 
     * @author  顾力行-gulixing@msn.com
     */
    @RequestMapping(value=Routes.Add, method = RequestMethod.POST)// consumes = MediaTypes.JSON
    @ResponseBody
    public Map<String, String> add(HttpServletRequest request,HttpServletResponse response) {
    	Map<String, String> ajaxMap = getAjaxMap();
    	Account account = new Account();
        Account a = getAccountFromRequest(request);
        User u = getUserFromRequest(request);
		BeanValidators.validateWithException(validator, a);
		BeanValidators.validateWithException(validator, u);
        if(!as.validateUnique(account.getName())){
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);//400
            ajaxMap.put("message", "帐户["+account.getName()+"]已存在，请使用其他名称进行注册！");
            return ajaxMap;
        }
        Long id = as.getDao().saveEntity(a).getId();
        u.setId(id);
        us.getDao().save(u);
        return ajaxMap;
    }
    
    private Account getAccountFromRequest(HttpServletRequest request){
    	 Account a = new Account();
         a.setName((String)request.getParameter("name"));
         a.setPassword((String)request.getParameter("password"));
         a.setRepeatPassword((String)request.getParameter("repeatPassword"));
         a.getRoleList().add(rService.findByName("STUDENT"));//赋角色
         if(!StringUtils.isEmpty(request.getParameter("unit"))){
 	    	Long unitId = Long.valueOf((String)request.getParameter("unit")); 
 	        a.setUnit(uns.getDao().findOne(unitId));
         }
    	 return a;
    }
    
    private User getUserFromRequest(HttpServletRequest request){
    	User user = new User();
    	user.setName((String)request.getParameter("username"));
    	user.setEmail((String)request.getParameter("email"));
    	user.setDegree((String)request.getParameter("degree"));
    	user.setGraduate((String)request.getParameter("graduate"));
    	user.setPhone((String)request.getParameter("phone"));
    	user.setTeacher(us.getDao().findOne(Long.valueOf((String)request.getParameter("teacher"))));
    	return user;
    }

}